import { createStore } from "vuex";
import { login, getinfo } from "~/api/managerAPI.js";
import { SetTokenLocalStorage } from "../composables/auth";

const store = createStore({
  state() {
    return {
      //用户信息
      user: {},
    };
  },
  getters: {},
  mutations: {
    //设置用户信息
    SET_USERINFO(state, user) {
      state.user = user;
    },
  },
  actions: {
    //异步操作，通过调用mutation，而不是直接改变状态值
    //登录
    userlogin({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            console.log("登录", res);
            SetTokenLocalStorage(res.token);
            resolve(res);
          })
          .catch((err) => {
            console.log("请求", err);
            reject(err);
          });
      });
    },
    //获取当前登录用户信息
    getinfo({ commit }) {
      return new Promise((resolve, reject) => {
        getinfo()
          .then((res) => {
            //console.log('getinfo',res)
            commit("SET_USERINFO", res);
            resolve(res);
          })
          .catch((err) => reject(err));
      });
    },
  },
  modules: {},
});

export default store;
